"""
@Project: pythonPro1
@Name: pcaFlower.py
@Author: linxin_liu
@Date: 2022/11/8 13:51
"""
from sklearn.datasets import load_iris
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
X, y = load_iris(return_X_y=True)
# 去中心化
X = X -X.mean(axis=0)
# 计算样本的协方差矩阵
C = np.cov(X, rowvar=False)
# 求解协方差矩阵的特征值和特征向量
eigen_vals, eigen_vecs = np.linalg.eig(C)
print("特征值：\n", eigen_vals)
print("特征向量：\n", eigen_vecs)
# 保留两个维度的特征向量(基)。
W = eigen_vecs[:, 0:2]
T = np.dot(X, W)
print(T[:10])

pca = PCA(n_components=2)
T2 = pca.fit_transform(X)
print(T2[0:10])
color = np.array(['r', 'g', 'b'])
plt.scatter(T[:, 0], T[:, 1], c=color[y])